#!/usr/bin/env perl

use strict;
use warnings;

die "Usage: $0 ucsc_bedtable1.txt ucsc_bedtable2.txt\n" unless @ARGV;
warn "Assuming first column to be \'BIN\'\n";

my ($match,$line_regex);
$match = "([^\t]*)";
$line_regex = "$match\t" x 5; #assuming first column to be BIN
$line_regex .= $match;

for my $table (@ARGV)
{
    open IN, "< $table" or die "Cannot open $table\n";
    my @generic;
    while (<IN>)
    {
	push @generic, &chr2no($2)."\t$3\t$4\t$6\n" if /$line_regex/;
    }
    close IN;
    open OUT, "> $table.generic" or die "Cannot create $table.generic\n";
    print OUT "chr\tstart\tend\tscore\n";
    print OUT @generic;
    close OUT;
    warn "Output written to $table.generic\n";
}

sub chr2no
{
    my $chr=shift;
    if ($chr =~ /chr(\d+)/)
    {
	return $1;
    } elsif ($chr eq 'chrX')
    {
	return 23;
    } elsif ($chr eq 'chrY')
    {
	return 24;
    } elsif ($chr eq 'chrmito')
    {
	return 25;
    } elsif ($chr eq 'chrXY')
    {
	return 26;
    } else
    {
	die "Unkown chromosome\n";
    }
}
